package sourceapi.client;

import sourceapi.client.mainpage.FunctionList;
import sourceapi.client.mainpage.Native;
import sourceapi.client.mainpage.SourceCode;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.http.client.*;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class SourceAPI implements EntryPoint, ValueChangeHandler<String>  {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	//private static final String SERVER_ERROR = "An error occurred while "
	//		+ "attempting to contact the server. Please check your network "
	//		+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	//private final GreetingServiceAsync greetingService = GWT
	//		.create(GreetingService.class);

	/**
	 * This is the entry point method.
	 */
	
	static public SearchBox MainSearchBox;

	
	public void onModuleLoad() {
		

		String url = GWT.getHostPageBaseURL() + "data/filelist.php";
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
		
		try {		
			builder.setCallback( new MenuManager() );
			builder.send();
		} catch (RequestException e) {
		  // Couldn't connect to server        
		}
		
		// Add history listener
	    History.addValueChangeHandler(this);
	    
	    MainSearchBox = new SearchBox();
	    
	    RootPanel.get("SearchSpace").add( MainSearchBox );	
		
	}
	
	public static boolean ShouldSearch(){
		
		String SearchPatern = SourceAPI.MainSearchBox.getText();
		
		return  SearchPatern.length() > 1;
		
	}
	
	public void onValueChange(ValueChangeEvent<String> event) {
		
		String Value = event.getValue();
		
		if( Value.length() == 0 )
			return;
		
		String ValueCall = Value.substring(2) ;
		GWT.log("Displaying: " + Value + " ("+ Value.charAt(0) +")", null);
		
		switch( Value.charAt(0) ){
		case 'f':
			Native.Display( ValueCall );
			break;
		case 'c':
			break;
		case 'l':
			FunctionList.Display( ValueCall );
			break;
		case 's':
			SourceCode.Display( ValueCall );
			break;
		}
		
	}
	
	
}
